package com.ytjj.qmyx.admin.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.admin.constants.RedisConstant;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description TODO
 * @ClassName CaptchaController
 *
 *
 * @Version 1.0
 **/

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private RedisService redisService;


    /**
     * @Description 获取验证码
     *
     *
     *
     * @Version 1.0
     **/
    @RequestMapping("/captchaVerify")
    public CommonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> resultMap = this.getResultMap();
        // 将key和base64返回给前端
        return CommonResult.success(resultMap);
    }


    /**
     * @Description 获取返回结果
     *
     *
     *
     * @Version 1.0
     **/
    public Map<String, String> getResultMap() {
        // 算术类型
        ArithmeticCaptcha specCaptcha = new ArithmeticCaptcha(130, 48);
        // 几位数运算，默认是两位
        specCaptcha.setLen(3);
        // 获取运算的公式：3+2=?
        specCaptcha.getArithmeticString();
        // 获取运算的结果：5
        String verCode = specCaptcha.text();
        String key = RedisConstant.CAPTCHA + UUID.randomUUID().toString();
        // 存入redis并设置过期时间为2分钟
        redisService.set(key, verCode);
        redisService.expire(key, RedisConstant.CAPTCHA_EXPIRE_TIME);
        Map<String, String> resultMap = new HashMap<>(2);
        resultMap.put("key", key);
        resultMap.put("image", specCaptcha.toBase64());
        return resultMap;
    }
}
